package dk.pekilidi.webapp.action;


import java.io.Serializable;
import dk.pekilidi.model.MBean;
import org.appfuse.service.GenericManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * User: msp
 * Date: 04-12-12
 * Time: 11:30
 */
@Scope("request")
@Component("mBeanForm")
public class MBeanForm extends BasePage implements Serializable {
    private GenericManager<MBean, Long> mbeanManager;
    private MBean mbean = new MBean();
    private Long id;

    @Autowired
    public void setMBeanManager(@Qualifier("mbeanManager") GenericManager<MBean, Long> manager) {
        this.mbeanManager = manager;
    }

    public MBean getMBean() {
        return mbean;
    }

    public void setMBean(MBean mbean) {
        this.mbean = mbean;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String delete() {
        mbeanManager.remove(mbean.getId());
        addMessage("mbean.deleted");

        return "list";
    }

    public String edit() {
        if (id == null) {
            id = new Long(getParameter("id"));
        }
        mbean = mbeanManager.get(id);

        return "edit";
    }

    public String save() {
        boolean isNew = (mbean.getId() == 0);
        mbeanManager.save(mbean);

        String key = (isNew) ? "mbean.added" : "mbean.updated";
        addMessage(key);

        if (isNew) {
            return "list";
        } else {
            return "edit";
        }
    }
}
